'use strict';

const Service = require('egg').Service;
const SysBranchModel = require('../../model/SysBranchModel');
const sysBranchModel = new SysBranchModel();
class sysBranchService extends Service {
/*
  * 添加单位
  */
  async addBranch(models) {
    return await sysBranchModel.addBranch(this.app, models);
  }
  /*
   * 查询所有单位
   */
  async findAllBranch() {
    return await sysBranchModel.findAllBranch(this.app);
  }
  /*
   * 查询单位详情
   */
  async findBranchByCode(code) {

    return await sysBranchModel.findBranchByCode(this.app, code);

  }
  async delBranch(code) {
    return await sysBranchModel.delBranch(this.app, code);
  }
  /*
   * 更新单位
   */
  async updateBranch(code, models) {
    return await sysBranchModel.updateBranch(this.app, code, models);
  }
  /*
   * 查询单位树
   */
  async querySysBranch() {
    // 1.查询所有单位列表
    const sysBranchList = await sysBranchModel.findAllBranch(this.app);
    if (!sysBranchList.length) {
      return [];
    }
    return this.convertBranchTree(sysBranchList, '130401');
  }

  /*
   * 将单位列表转换成单位树 数据
   * @param {[sysMenus]} sysMenusList 单位数组
   * @param {int} rootId 根目录ID
   */
  convertBranchTree(sysBranchList, code) {
    // 查找根目录
    const rootMenu = sysBranchList.find(item => {
      return item.code == code;
    });
    // 单位树对象初始化
    const sysBrachesTree = {
      rootMenu,
    };
    sysBrachesTree.rootMenu.children = this.getChildrenBracnches(sysBranchList, rootMenu.code);
    return sysBrachesTree;
  }
  /*
   * 查找子节点单位列表
   * @param {[sysBranchList]} sysBranchList 单位数组
   * @param {string} code 父节code
   */
  getChildrenBracnches(sysBranchList, parentCode) {
    const _childrenSysBranches = [];
    // 查找所有子节点
    const childrenSysBranches = sysBranchList.filter(item => {
      return item.parent_code == parentCode;
    });
    if (childrenSysBranches && childrenSysBranches.length > 0) {
      for (const sysMenu of childrenSysBranches) {
        // 如果单位数据 1: 目录；2:页面  则还是有下一级单位，需要递归查找
        if (sysMenu.type == 1 || sysMenu.type == 2) {
          sysMenu.children = this.getChildrenBracnches(sysBranchList, sysMenu.code);
          _childrenSysBranches.push(sysMenu);
        } else {
          _childrenSysBranches.push(sysMenu);
        }
        _childrenSysBranches.push(sysMenu);
      }
    }
    return childrenSysBranches;
  }
  /*
   * 宠物注册表中有的区域代码，不能删除该区域
   */
  async findBranchByCodeOfPetRegister(code) {
    const result = await sysBranchModel.findBranchByCodeOfPetRegister(this.app, code);
    return result;
  }
 /*
   * 查询SUOYOU单位
   */
  async queryAllBranch() {
    // 1.查询所有单位列表
    const sysBranchList = await sysBranchModel.queryAllBranch(this.app);
    return sysBranchList;
  }
  /**
   * 查询所有的子级单位
   */
  async queryLeafBranch(request) {
      return await sysBranchModel.queryLeafBranch(this.app, request);
  }
}
module.exports = sysBranchService;
